// Copyright (c) 2010 Marcos David Marín Amador <marcosmarin@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

function cfaqs_build_post_msg_url() {
	var params = cfaqs_get_board_and_topic();
	return "/boards/post.php?board=" + params["board"] + "&topic=" + params["topic"];
}

function cfaqs_build_post_topic_url() {
	var params = cfaqs_get_board_and_topic();
	return "/boards/post.php?board=" + params["board"];
}

// TODO: Update to use new URLs  (works for now, but for how long?)
function cfaqs_build_msg_list_url() {
	var params = cfaqs_get_board_and_topic();
	return "http://www.gamefaqs.com/boards/genmessage.php?board="
		+ params["board"] + "&topic=" + params["topic"];
}

function cfaqs_build_topic_list_url() {
	var params = cfaqs_get_board_and_topic();
	return "http://www.gamefaqs.com/boards/genmessage.php?board=" + params["board"];
}

// posts message with no preview, if title param is provided post topic
function cfaqs_post_message(msg, title) {
	var url = (title ? cfaqs_build_post_topic_url() : cfaqs_build_post_msg_url());
	msg = escape(msg).replace(/\+/g, "%2B");
	
	var data = (title ? "topictitle=" + title + "&" : "")
		+ "message=" + msg + "&post=Preview Message";
	
	$.ajax({
		type: "POST",
		url: url,
		processData: false,
		data: data,
		success: function(html) {
			var id = html.match(/<input\b[^>]+?\bname="post_id"[^>]+?\bvalue="([^"]*)"/)[1];
			var uid = html.match(/<input\b[^>]+?\bname="uid"[^>]+?\bvalue="([^"]*)"/)[1];
			
			$.post(url, { post: "Post Message", post_id: id, uid: uid }, function(html) {
				if (title) {
					location.href = cfaqs_build_topic_list_url();
				} else {
					location.href = cfaqs_build_msg_list_url();
				}
			})
		},
		dataType: "html",
		contentType: "application/x-www-form-urlencoded"
	});
}

function cfaqs_build_post_msg_form(settings) {
	function wrap_text(tag) {
		var text = document.getElementById("cfaqs-quickpost-text");
		var before_text = text.value.substring(0, text.selectionStart);
		var selected_text = text.value.substring(text.selectionStart, text.selectionEnd);
		var after_text = text.value.substring(text.selectionEnd, text.value.length);
		
		selected_text = "<" + tag + ">" + selected_text + "</" + tag + ">";
		
		text.value = before_text + selected_text + after_text;
		
		var caret_position = before_text.length + selected_text.length - 3 - tag.length;
		text.setSelectionRange(caret_position, caret_position);
	}
	
	var containing_body = document.createElement("div");
	containing_body.className = "body";
	
	var form = document.createElement("form");
	form.enctype  = "application/x-www-form-urlencoded; charset=ISO-8859-1";
	form.id = "cfaqs-quickpost-form";
	form.method = "POST";
	form.action = cfaqs_build_post_msg_url();
	
	var pod = document.createElement("div");
	pod.className = "pod";
	
	var head = document.createElement("div");
	head.className = "head";
	
	var title = document.createElement("h2");
	title.className = "title";
	title.innerText = "Post New Message";
	
	var body = document.createElement("div");
	body.className = "body";
	
	var containing_p = document.createElement("p");
	
	var toolbar = document.createElement("span");
	toolbar.id = "cfaqs-quickpost-toolbar";
	
	var bold = document.createElement("button");
	bold.id = "cfaqs-quickpost-bold";
	bold.innerHTML = "<b>bold</b>";
	bold.tabIndex = -1;
	bold.onclick = function(e) {
		e.preventDefault();
		wrap_text("b");
	}
	
	var italics = document.createElement("button");
	italics.id = "cfaqs-quickpost-italics";
	italics.innerHTML = "<i>italic</i>";
	italics.tabIndex = -1;
	italics.onclick = function(e) {
		e.preventDefault();
		wrap_text("i");
	}
	
	var text = document.createElement("textarea");
	text.id = "cfaqs-quickpost-text";
	text.cols = "100";
	text.rows = "20";
	text.name = "message";
	
	if (settings.signature) {
		text.value = "\n---\n" + settings.signature;
	}
	
	var details = document.createElement("div");
	details.className = "details";
	details.innerHTML = "<p><b>Your Message:</b></p><p>Enter your message text below.</p>";
	
	var post = document.createElement("input");
	post.id = "cfaqs-quickpost-post-button";
	post.type = "submit";
	post.value = "Post Message";
	post.onclick = function(event) {
		event.preventDefault();
		post.disabled = true;
		
		cfaqs_post_message(text.value);
	}
	
	var preview = document.createElement("input");
	preview.id = "cfaqs-quickpost-preview-button";
	preview.type = "submit";
	preview.value = "Preview Message";
	preview.name = "post";
	
	var spellcheck = document.createElement("input");
	spellcheck.id = "cfaqs-quickpost-spellcheck-button";
	spellcheck.type = "submit";
	spellcheck.value = "Preview and Spellcheck Message";
	spellcheck.name = "post";
	
	var reset = document.createElement("input");
	reset.id = "cfaqs-quickpost-reset-button";
	reset.type = "reset";
	reset.value = "Reset";
	reset.name = "reset";
	reset.onclick = function(event) {
		event.preventDefault()
		if (confirm("Are you sure? This will clear your entire post so far.")) {
			
			if (settings.signature) {
				text.value = "\n---\n" + settings.signature;
			} else {
				text.value = "";
			}
			
			text.setSelectionRange(0, 0);
		}
	}
	
	// connect tree
	containing_body.appendChild(form);
	
	form.appendChild(pod);
	
	pod.appendChild(head);
	pod.appendChild(body);
	
	head.appendChild(title);
	
	body.appendChild(details);
	
	containing_p.appendChild(text);
	
	toolbar.appendChild(bold);
	toolbar.appendChild(italics);
	
	details.appendChild(toolbar);
	details.appendChild(containing_p);
	details.appendChild(post);
	details.appendChild(preview);
	details.appendChild(spellcheck);
	details.appendChild(reset);
	
	return containing_body;
}

function cfaqs_build_post_topic_form(settings) {
	var form = cfaqs_build_post_msg_form(settings);
	form.id = "cfaqs-quicktopic-div";
	
	var input = document.createElement("input");
	input.id = "cfaqs-quicktopic-title";
	input.type = "text";
	input.size = 70;
	input.maxLength = 80;
	input.name = "topictitle";
	input.value = "";
	
	$(".title", form).text("Create New Topic");
	
	$(".details p:first", form).before("<p><b>Topic Title:</b><br></p>");
	
	$(".details p:first", form)[0].appendChild(input);
	
	$(".details p:first", form).append("<br> (Between 5 and 80 characters in length)");
	
	$(".details p:first", form).before(
		"<p>To create a new topic, enter a title for the " +
		"topic below and create the first message.</p>");
	
	$("form:first", form)[0].action = cfaqs_build_post_topic_url();
	
	$("#cfaqs-quickpost-post-button", form)[0].onclick = function(event) {
		event.preventDefault();
		this.disabled = true;
		
		cfaqs_post_message($("#cfaqs-quickpost-text", form)[0].value, input.value);
	}
	
	return form;
}